import logging
import random

# 图形验证码
from django.views import View

from celery_tasks.sms.tasks import send_sms_code
from response_code import RETCODE, err_msg
from . import constants
from .libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http

logger = logging.getLogger("django")

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        # 获取图像验证码

        text, image = captcha.generate_captcha()
        logger.info("生成的图形验证码为 %s",  text, exc_info=1)
        # text存到redis2号库
        redis_conn = get_redis_connection("verify_code")
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)  # 过期时间5分钟
        # 返回图片
        return http.HttpResponse(image, content_type="image/jpg")


class SMSCodeView(View):
    """发送短信验证码"""

    def get(self, request, mobile):
        uuid = request.GET.get("uuid")
        image_code_client = request.GET.get("image_code")
        if not all([uuid, image_code_client]):
            return http.HttpResponseForbidden("缺少必传参数")

        image_code_key = 'img_%s' % uuid  # redis中存储图形验证码的key

        redis_conn = get_redis_connection("verify_code")
        # 判断发短信的间隔是否超过60秒，超过则可重新发送
        send_flag = redis_conn.get("send_flag_%s" % '18344561746')
        if send_flag :
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'err_msg': err_msg[RETCODE.THROTTLINGERR]})
        # 对比图形验证码
        image_code_server = redis_conn.get(image_code_key)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'err_msg': '图形验证码已失效'})
        # 删除图像验证码，以保证唯一
        redis_conn.delete(image_code_key)
        # 校验图形验证码,类型不同需要转
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'err_msg': err_msg[RETCODE.IMAGECODEERR]})

        # 生成短信验证码,生成随机6位数,不够6位则补0，如000006
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info("生成的短信验证码为 %s", sms_code, exc_info=1)

        #生成管道，打包好命令一次性发送给redis,减少能耗
        pl = redis_conn.pipeline()
        # 保存短信验证码
        pl.setex("sms_%s" % '18344561746', constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送短信的标志，避免用户频繁发送短信
        pl.setex("send_flag_%s" % '18344561746', constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行
        pl.execute()

        # # 发送短信,/ 会得到浮点数，//得到整数
        # result = CCP().send_template_sms('18344561746', [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60],
        #                                  constants.SEND_SMS_TEMPLATE_ID)
        # 使用celery调用发送短信，以保证代码不会被阻塞
        result = send_sms_code.delay(sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60, constants.SEND_SMS_TEMPLATE_ID)
        logger.info(result)

        return http.JsonResponse({'code': RETCODE.OK, 'err_msg': err_msg[RETCODE.OK]})

